package cn.wolfcode.shop.cloud.service.impl;


import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.OrderInfoMapper;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.util.SeckillGoodsCodeMsg;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class OrderInfoServiceImpl implements IOrderInfoService {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    @Transactional
    public String seckill(Long seckillId,Long userId) {
        //杀的业务
        //减少库存 -1
        int row = seckillGoodService.decrCount(seckillId);
        if (row==0){
            throw new BusinessException(SeckillGoodsCodeMsg.SECKILL_OVER);
        }

        //创建订单信息
        String orderNo = createOrderInfo(seckillId,userId);
        //创建秒杀订单信息,简单来说就是用sql语句插入一条数据到数据库
        seckillOrderService.createSeckillOrder(seckillId, userId, orderNo);
        return orderNo;
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        return orderInfoMapper.findByOrderNo(orderNo);
    }

    @Override
    public int changeOrderInfoStatus(String orderNo, Integer status) {
        return orderInfoMapper.changeOrderInfoStatus(orderNo,status);
    }

    @Override
    public int updateStatus(String orderNo, Integer status) {
        return orderInfoMapper.updateStatus(orderNo,status);
    }

    private String createOrderInfo(Long seckillId,Long userId) {
        SeckillGoodVo seckillGoodVo = seckillGoodService.findById(seckillId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodCount(seckillGoodVo.getStockCount());
        orderInfo.setGoodId(seckillGoodVo.getGoodId());
        orderInfo.setGoodImg(seckillGoodVo.getGoodImg());
        orderInfo.setGoodName(seckillGoodVo.getGoodName());
        orderInfo.setGoodPrice(seckillGoodVo.getGoodPrice());
        orderInfo.setOrderNo(new IdGenerateUtil().nextId()+"");
        orderInfo.setSeckillPrice(seckillGoodVo.getSeckillPrice());
        orderInfo.setUserId(userId);
        orderInfoMapper.save(orderInfo);

        return orderInfo.getOrderNo();
    }

}

